package ex.com.jm.food.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import ex.com.jm.food.dao.AdminCompanyDiscountDao;
import ex.com.jm.food.entity.CompanyDiscount;

public class AdminCompanyDiscountDaoImpl extends HibernateDaoSupport implements
		AdminCompanyDiscountDao {

	public AdminCompanyDiscountDaoImpl() {
		// TODO Auto-generated constructor stub
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List<CompanyDiscount> getCompanyDiscounts(final int initPage,final int pageRow,
			final String name) {
		// TODO Auto-generated method stub
		Object comdis=this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				String hql="from CompanyDiscount where 1=1 ";
				
				if(name!=null&&!name.equals("")){
					hql+=" and cdName like '%"+name+"%'";
				}
				Query query=session.createQuery(hql).setFetchSize(initPage).setMaxResults(pageRow);
				return query.list();
			}
		});
		return (List<CompanyDiscount>) comdis;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public int cdCount(final String name) {
		// TODO Auto-generated method stub
		int count=this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
	String hql="from CompanyDiscount where 1=1 ";
				
				if(name!=null&&!name.equals("")){
					hql+=" and cdName like '%"+name+"%'";
				}
				Query query=session.createQuery(hql);
				return query.list().size();
			}
		});
		return count;
	}

	@Override
	public Object saveComDis(CompanyDiscount companyDiscount) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().save(companyDiscount);
	}

	@Override
	public void updateComDis(CompanyDiscount companyDiscount) {
		// TODO Auto-generated method stub
         this.getHibernateTemplate().update(companyDiscount);
	}

	@Override
	public CompanyDiscount editComDis(Integer id) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(CompanyDiscount.class, id);
	}

	@Override
	public void delComDis(Integer id) {
		// TODO Auto-generated method stub
       this.getHibernateTemplate().delete(this.getHibernateTemplate().get(CompanyDiscount.class, id));
	}

}
